package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadController {

    @RequestMapping("/upload")
    public String upload(MultipartFile myFile, HttpServletRequest request) {
        //生成唯一的文件名称
        //uuid 生成的文件名会有- 替换掉
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //获取原始文件名
        String originalFilename = myFile.getOriginalFilename();
        //获取最后一个.出现的索引
        int lastIndexOf = originalFilename.lastIndexOf(".");
        //获取文件的后缀名
        String extendName = originalFilename.substring(lastIndexOf);
        System.out.println(extendName);

        //动态获取服务器所在的路径 uuid.jpg (真实(绝对)的路径)
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
        System.out.println(realPath + "/" + uuid + extendName);

        //文件上传
        try {
            File file = new File(realPath);
            //如果文件不存在，则创建
            if (!file.exists()) {
                file.mkdirs();
            }
            //D:/java/Project/SSM_374/SpringMVC02_04_upload/src/main/webapp/upload/1.jpg
            myFile.transferTo(new File(realPath + "/" + uuid + extendName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // redirect 重定向
        return "redirect:/pages/message.jsp";
    }
}
